package helloworld.service.administrate;

import helloworld.dao.administrate.RoleDao;
import helloworld.dao.administrate.UserDao;
import helloworld.entity.administrate.Role;
import helloworld.entity.administrate.User;
import helloworld.modules.hibernate.Page;
import helloworld.modules.hibernate.PropertyFilter;
import helloworld.modules.utils.reflection.ConvertUtils;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService implements IUserService {
	
	private UserDao userDao;
	private RoleDao roleDao;

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#searchUser(helloworld.modules.hibernate.Page, java.util.List)
	 */
	@Transactional(readOnly = true)
	public Page<User> searchUser(final Page<User> page,
			final List<PropertyFilter> filters) {
		return userDao.findPage(page, filters);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#getAllRole()
	 */
	@Transactional(readOnly = true)
	public List<Role> getAllRole() {
		return roleDao.getAll("id", true);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#getUser(java.lang.Long)
	 */
	public User getUser(Long id) {
		return userDao.get(id);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#getRole(java.lang.Long)
	 */
	public Role getRole(Long id) {
		return roleDao.get(id);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#saveUser(helloworld.entity.administrate.User, java.util.List)
	 */
	public void saveUser(User entity, List<Long> checkedRoleIds) {
		userDao.save(entity, checkedRoleIds);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#saveRole(helloworld.entity.administrate.Role)
	 */
	public void saveRole(Role entity) {
		roleDao.save(entity);
	}

	/* (non-Javadoc)
	 * @see helloworld.service.administrate.IUserS#searchRole(java.util.List)
	 */
	public List<Role> searchRole(List<PropertyFilter> filters) {
		return roleDao.find(filters);
	}

	public List<Long> getRoleIds(Long userId) {
		User user = userDao.get(userId);
		List<Role> roleList = user.getRoleList();
		return ConvertUtils.convertElementPropertyToList(roleList, "id");
	}

	public User getUserByUsername(String userName) {
		return userDao.findUniqueBy("username", userName);
	}

	
}
